package com.tt5.services.vertx

import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.core.json.get
import io.vertx.kotlin.coroutines.dispatcher
import io.vertx.mysqlclient.MySQLBuilder
import io.vertx.redis.client.Redis
import io.vertx.redis.client.RedisOptions
import io.vertx.sqlclient.Pool
import io.vertx.sqlclient.PoolOptions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

private lateinit var redisOptions: RedisOptions
private lateinit var redisClient: Redis
var redisKeyPrefix = ""
fun Vertx.initRedisOptions(options: JsonObject) {
  redisKeyPrefix = options["keyPrefix"] ?: ""
  redisOptions = RedisOptions(options)
  redisClient = Redis.createClient(this, redisOptions)
}

@OptIn(DelicateCoroutinesApi::class)
fun Vertx.launch(block: suspend CoroutineScope.() -> Unit) {
  GlobalScope.launch(dispatcher(), block = block)
}

/**
 * 获取[name]对应的共享数据库连接池，需保证在使用前已经初始化
 */
fun Vertx.sharedDbPool(name: String = PoolOptions.DEFAULT_NAME): Pool {
  return MySQLBuilder.pool().with(PoolOptions().setName(name).setShared(true)).using(this).build()
}

val Vertx.redis: Redis
  get() = redisClient
